package com.glodon.async.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.glodon.async.service.RemoteService;
import com.glodon.async.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.*;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private RemoteService remoteService;

    @Override
    public JSONObject getUserInfo(String userId) {

        JSONObject userName = remoteService.getUserName(userId);
        JSONObject userAmount = remoteService.getUserAmount(userId);
        JSONObject userCash = remoteService.getUserCash(userId);

        JSONObject result = new JSONObject();
        result.putAll(userName);
        result.putAll(userAmount);
        result.putAll(userCash);

        return result;
    }

    @Override
    public JSONObject getUserInfoAsync(String userId) {

        Callable<JSONObject> userCall = new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                JSONObject userName = remoteService.getUserName(userId);
                return userName;
            }
        };
        FutureTask<JSONObject> userFuture = new FutureTask<JSONObject>(userCall);
        new Thread(userFuture).start();

        Callable<JSONObject> userAmountCall = new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                JSONObject userAmount = remoteService.getUserAmount(userId);
                return userAmount;
            }
        };
        FutureTask<JSONObject> userAmountFuture = new FutureTask<JSONObject>(userAmountCall);
        new Thread(userAmountFuture).start();


        Callable<JSONObject> userCashCall = new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                JSONObject userCash = remoteService.getUserCash(userId);
                return userCash;
            }
        };
        FutureTask<JSONObject> userCashFuture = new FutureTask<JSONObject>(userCashCall);
        new Thread(userCashFuture).start();

        JSONObject result = new JSONObject();

        try {
            JSONObject userJson = userFuture.get();// 1/s
            JSONObject amountJson = userAmountFuture.get(); //1/s
            JSONObject cashJson = userCashFuture.get();//3s

            result.putAll(userJson);
            result.putAll(amountJson);
            result.putAll(cashJson);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return result;
    }

}
